<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" type="text/css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="./resources/prism/prism.css" type="text/css">
    <link rel="stylesheet" href="../css/ol.css" type="text/css">
    <link rel="stylesheet" href="./resources/layout.css" type="text/css">
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <link rel="stylesheet" href="raster.css">
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="./resources/zeroclipboard/ZeroClipboard.min.js"></script>
    <title>Raster Source</title>
  </head>
  <body>

    <header class="navbar" role="navigation">
      <div class="container">
        <div class="display-table pull-left" id="navbar-logo-container">
          <a class="navbar-brand" href="./"><img src="./resources/logo-70x70.png">&nbsp;OpenLayers Examples</a>
        </div>
        <!-- menu items that get hidden below 768px width -->
        <nav class='collapse navbar-collapse navbar-responsive-collapse'>
          <ul class="nav navbar-nav pull-right">
            <li><a href="../doc">Docs</a></li>
            <li><a class="active" href="index.html">Examples</a></li>
            <li><a href="../apidoc">API</a></li>
            <li><a href="https://github.com/openlayers/openlayers">Code</a></li>
          </ul>
        </nav>
      </div>
    </header>

    <div class="container-fluid">

      <div id="latest-check" class="alert alert-warning alert-dismissible" role="alert" style="display:none">
        <button id="latest-dismiss" type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        This example uses OpenLayers v<span>4.4.2</span>. The <a id="latest-link" href="#" class="alert-link">latest</a> is v<span id="latest-version"></span>.
      </div>

      <div class="row-fluid">
        <div class="span12">
          <h4 id="title">Raster Source</h4>
          <div class="rel">
  <div id="map" class="map"></div>
  <div id="plot"></div>
</div>

        </div>
      </div>

      <div class="row-fluid">
        <div class="span12">
          <p id="shortdesc">Demonstrates pixelwise operations with a raster source.</p>
          <div id="docs"><p>
  This example uses a <code>ol.source.Raster</code> to generate data
  based on another source.  The raster source accepts any number of
  input sources (tile or image based) and runs a pipeline of
  operations on the input pixels.  The return from the final
  operation is used as the data for the output source.
</p> <p>
  In this case, a single tiled source of imagery is used as input.
  For each pixel, the Vegetation Greenness Index
  (<a href="http://www.tandfonline.com/doi/abs/10.1080/10106040108542184#.Vb90ITBViko">VGI</a>)
  is calculated from the input pixels.  A second operation colors
  those pixels based on a threshold value (values above the
  threshold are green and those below are transparent).
</p>
</div>
          <div id="api-links">Related API documentation: <ul class="inline"><li><a href="../apidoc/ol.Map.html" title="API documentation for ol.Map">ol.Map</a></li>,<li><a href="../apidoc/ol.View.html" title="API documentation for ol.View">ol.View</a></li>,<li><a href="../apidoc/ol.layer.Image.html" title="API documentation for ol.layer.Image">ol.layer.Image</a></li>,<li><a href="../apidoc/ol.layer.Tile.html" title="API documentation for ol.layer.Tile">ol.layer.Tile</a></li>,<li><a href="../apidoc/ol.source.BingMaps.html" title="API documentation for ol.source.BingMaps">ol.source.BingMaps</a></li>,<li><a href="../apidoc/ol.source.Raster.html" title="API documentation for ol.source.Raster">ol.source.Raster</a></li></ul></div>
        </div>
      </div>

      <div class="row-fluid">
        <div id="source-controls">
          <a id="copy-button"><i class="fa fa-clipboard"></i> Copy</a>
          <a id="codepen-button"><i class="fa fa-codepen"></i> Edit</a>
        </div>
        <form method="POST" id="codepen-form" target="_blank" action="https://codepen.io/pen/define/">
          <textarea class="hidden" name="title">Raster Source</textarea>
          <textarea class="hidden" name="description">Demonstrates pixelwise operations with a raster source.</textarea>
          <textarea class="hidden" name="js">// this example uses d3 for which we don&#x27;t have an externs file.
var minVgi &#x3D; 0;
var maxVgi &#x3D; 0.25;
var bins &#x3D; 10;


/**
 * Calculate the Vegetation Greenness Index (VGI) from an input pixel.  This
 * is a rough estimate assuming that pixel values correspond to reflectance.
 * @param {Array.&lt;number&gt;} pixel An array of [R, G, B, A] values.
 * @return {number} The VGI value for the given pixel.
 */
function vgi(pixel) {
  var r &#x3D; pixel[0] / 255;
  var g &#x3D; pixel[1] / 255;
  var b &#x3D; pixel[2] / 255;
  return (2 * g - r - b) / (2 * g + r + b);
}


/**
 * Summarize values for a histogram.
 * @param {numver} value A VGI value.
 * @param {Object} counts An object for keeping track of VGI counts.
 */
function summarize(value, counts) {
  var min &#x3D; counts.min;
  var max &#x3D; counts.max;
  var num &#x3D; counts.values.length;
  if (value &lt; min) {
    // do nothing
  } else if (value &gt;&#x3D; max) {
    counts.values[num - 1] +&#x3D; 1;
  } else {
    var index &#x3D; Math.floor((value - min) / counts.delta);
    counts.values[index] +&#x3D; 1;
  }
}


/**
 * Use aerial imagery as the input data for the raster source.
 */
var bing &#x3D; new ol.source.BingMaps({
  key: &#x27;Your Bing Maps Key from http://www.bingmapsportal.com/ here&#x27;,
  imagerySet: &#x27;Aerial&#x27;
});


/**
 * Create a raster source where pixels with VGI values above a threshold will
 * be colored green.
 */
var raster &#x3D; new ol.source.Raster({
  sources: [bing],
  /**
   * Run calculations on pixel data.
   * @param {Array} pixels List of pixels (one per source).
   * @param {Object} data User data object.
   * @return {Array} The output pixel.
   */
  operation: function(pixels, data) {
    var pixel &#x3D; pixels[0];
    var value &#x3D; vgi(pixel);
    summarize(value, data.counts);
    if (value &gt;&#x3D; data.threshold) {
      pixel[0] &#x3D; 0;
      pixel[1] &#x3D; 255;
      pixel[2] &#x3D; 0;
      pixel[3] &#x3D; 128;
    } else {
      pixel[3] &#x3D; 0;
    }
    return pixel;
  },
  lib: {
    vgi: vgi,
    summarize: summarize
  }
});
raster.set(&#x27;threshold&#x27;, 0.1);

function createCounts(min, max, num) {
  var values &#x3D; new Array(num);
  for (var i &#x3D; 0; i &lt; num; ++i) {
    values[i] &#x3D; 0;
  }
  return {
    min: min,
    max: max,
    values: values,
    delta: (max - min) / num
  };
}

raster.on(&#x27;beforeoperations&#x27;, function(event) {
  event.data.counts &#x3D; createCounts(minVgi, maxVgi, bins);
  event.data.threshold &#x3D; raster.get(&#x27;threshold&#x27;);
});

raster.on(&#x27;afteroperations&#x27;, function(event) {
  schedulePlot(event.resolution, event.data.counts, event.data.threshold);
});

var map &#x3D; new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: bing
    }),
    new ol.layer.Image({
      source: raster
    })
  ],
  target: &#x27;map&#x27;,
  view: new ol.View({
    center: [-9651695, 4937351],
    zoom: 13,
    minZoom: 12,
    maxZoom: 19
  })
});


var timer &#x3D; null;
function schedulePlot(resolution, counts, threshold) {
  if (timer) {
    clearTimeout(timer);
    timer &#x3D; null;
  }
  timer &#x3D; setTimeout(plot.bind(null, resolution, counts, threshold), 1000 / 60);
}

var barWidth &#x3D; 15;
var plotHeight &#x3D; 150;
var chart &#x3D; d3.select(&#x27;#plot&#x27;).append(&#x27;svg&#x27;)
    .attr(&#x27;width&#x27;, barWidth * bins)
    .attr(&#x27;height&#x27;, plotHeight);

var chartRect &#x3D; chart[0][0].getBoundingClientRect();

var tip &#x3D; d3.select(document.body).append(&#x27;div&#x27;)
    .attr(&#x27;class&#x27;, &#x27;tip&#x27;);

function plot(resolution, counts, threshold) {
  var yScale &#x3D; d3.scale.linear()
      .domain([0, d3.max(counts.values)])
      .range([0, plotHeight]);

  var bar &#x3D; chart.selectAll(&#x27;rect&#x27;).data(counts.values);

  bar.enter().append(&#x27;rect&#x27;);

  bar.attr(&#x27;class&#x27;, function(count, index) {
    var value &#x3D; counts.min + (index * counts.delta);
    return &#x27;bar&#x27; + (value &gt;&#x3D; threshold ? &#x27; selected&#x27; : &#x27;&#x27;);
  })
      .attr(&#x27;width&#x27;, barWidth - 2);

  bar.transition().attr(&#x27;transform&#x27;, function(value, index) {
    return &#x27;translate(&#x27; + (index * barWidth) + &#x27;, &#x27; +
        (plotHeight - yScale(value)) + &#x27;)&#x27;;
  })
      .attr(&#x27;height&#x27;, yScale);

  bar.on(&#x27;mousemove&#x27;, function(count, index) {
    var threshold &#x3D; counts.min + (index * counts.delta);
    if (raster.get(&#x27;threshold&#x27;) !&#x3D;&#x3D; threshold) {
      raster.set(&#x27;threshold&#x27;, threshold);
      raster.changed();
    }
  });

  bar.on(&#x27;mouseover&#x27;, function(count, index) {
    var area &#x3D; 0;
    for (var i &#x3D; counts.values.length - 1; i &gt;&#x3D; index; --i) {
      area +&#x3D; resolution * resolution * counts.values[i];
    }
    tip.html(message(counts.min + (index * counts.delta), area));
    tip.style(&#x27;display&#x27;, &#x27;block&#x27;);
    tip.transition().style({
      left: (chartRect.left + (index * barWidth) + (barWidth / 2)) + &#x27;px&#x27;,
      top: (d3.event.y - 60) + &#x27;px&#x27;,
      opacity: 1
    });
  });

  bar.on(&#x27;mouseout&#x27;, function() {
    tip.transition().style(&#x27;opacity&#x27;, 0).each(&#x27;end&#x27;, function() {
      tip.style(&#x27;display&#x27;, &#x27;none&#x27;);
    });
  });

}

function message(value, area) {
  var acres &#x3D; (area / 4046.86).toFixed(0).replace(/\B(?&#x3D;(\d{3})+(?!\d))/g, &#x27;,&#x27;);
  return acres + &#x27; acres at&lt;br&gt;&#x27; + value.toFixed(2) + &#x27; VGI or above&#x27;;
}
</textarea>
          <textarea class="hidden" name="css">.rel {
  position: relative
}

#plot {
  pointer-events: none;
  position: absolute;
  bottom: 10px;
  left: 10px;
}

.bar {
  pointer-events: auto;
  fill: #AFAFB9;
}

.bar.selected {
  fill: green;
}

.tip {
  position: absolute;
  background: black;
  color: white;
  padding: 6px;
  font-size: 12px;
  border-radius: 4px;
  margin-bottom: 10px;
  display: none;
  opacity: 0;
}
</textarea>
          <textarea class="hidden" name="html">&lt;div class&#x3D;&quot;rel&quot;&gt;
  &lt;div id&#x3D;&quot;map&quot; class&#x3D;&quot;map&quot;&gt;&lt;/div&gt;
  &lt;div id&#x3D;&quot;plot&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
</textarea>
          <input type="hidden" name="resources" value="https://openlayers.org/en/v4.4.2/css/ol.css,https://openlayers.org/en/v4.4.2/build/ol.js,https://d3js.org/d3.v3.min.js">
          <input type="hidden" name="data">
        </form>
        <pre><code id="example-source" class="language-markup">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Raster Source&lt;/title&gt;
    &lt;link rel="stylesheet" href="https://openlayers.org/en/v4.4.2/css/ol.css" type="text/css"&gt;
    &lt;!-- The line below is only needed for old environments like Internet Explorer and Android 4.x --&gt;
    &lt;script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"&gt;&lt;/script&gt;
    &lt;script src="https://openlayers.org/en/v4.4.2/build/ol.js"&gt;&lt;/script&gt;
    &lt;script src&#x3D;&quot;https://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
    &lt;style&gt;
      .rel {
        position: relative
      }

      #plot {
        pointer-events: none;
        position: absolute;
        bottom: 10px;
        left: 10px;
      }

      .bar {
        pointer-events: auto;
        fill: #AFAFB9;
      }

      .bar.selected {
        fill: green;
      }

      .tip {
        position: absolute;
        background: black;
        color: white;
        padding: 6px;
        font-size: 12px;
        border-radius: 4px;
        margin-bottom: 10px;
        display: none;
        opacity: 0;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class&#x3D;&quot;rel&quot;&gt;
      &lt;div id&#x3D;&quot;map&quot; class&#x3D;&quot;map&quot;&gt;&lt;/div&gt;
      &lt;div id&#x3D;&quot;plot&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script&gt;
      // this example uses d3 for which we don&#x27;t have an externs file.
      var minVgi &#x3D; 0;
      var maxVgi &#x3D; 0.25;
      var bins &#x3D; 10;


      /**
       * Calculate the Vegetation Greenness Index (VGI) from an input pixel.  This
       * is a rough estimate assuming that pixel values correspond to reflectance.
       * @param {Array.&lt;number&gt;} pixel An array of [R, G, B, A] values.
       * @return {number} The VGI value for the given pixel.
       */
      function vgi(pixel) {
        var r &#x3D; pixel[0] / 255;
        var g &#x3D; pixel[1] / 255;
        var b &#x3D; pixel[2] / 255;
        return (2 * g - r - b) / (2 * g + r + b);
      }


      /**
       * Summarize values for a histogram.
       * @param {numver} value A VGI value.
       * @param {Object} counts An object for keeping track of VGI counts.
       */
      function summarize(value, counts) {
        var min &#x3D; counts.min;
        var max &#x3D; counts.max;
        var num &#x3D; counts.values.length;
        if (value &lt; min) {
          // do nothing
        } else if (value &gt;&#x3D; max) {
          counts.values[num - 1] +&#x3D; 1;
        } else {
          var index &#x3D; Math.floor((value - min) / counts.delta);
          counts.values[index] +&#x3D; 1;
        }
      }


      /**
       * Use aerial imagery as the input data for the raster source.
       */
      var bing &#x3D; new ol.source.BingMaps({
        key: &#x27;Your Bing Maps Key from http://www.bingmapsportal.com/ here&#x27;,
        imagerySet: &#x27;Aerial&#x27;
      });


      /**
       * Create a raster source where pixels with VGI values above a threshold will
       * be colored green.
       */
      var raster &#x3D; new ol.source.Raster({
        sources: [bing],
        /**
         * Run calculations on pixel data.
         * @param {Array} pixels List of pixels (one per source).
         * @param {Object} data User data object.
         * @return {Array} The output pixel.
         */
        operation: function(pixels, data) {
          var pixel &#x3D; pixels[0];
          var value &#x3D; vgi(pixel);
          summarize(value, data.counts);
          if (value &gt;&#x3D; data.threshold) {
            pixel[0] &#x3D; 0;
            pixel[1] &#x3D; 255;
            pixel[2] &#x3D; 0;
            pixel[3] &#x3D; 128;
          } else {
            pixel[3] &#x3D; 0;
          }
          return pixel;
        },
        lib: {
          vgi: vgi,
          summarize: summarize
        }
      });
      raster.set(&#x27;threshold&#x27;, 0.1);

      function createCounts(min, max, num) {
        var values &#x3D; new Array(num);
        for (var i &#x3D; 0; i &lt; num; ++i) {
          values[i] &#x3D; 0;
        }
        return {
          min: min,
          max: max,
          values: values,
          delta: (max - min) / num
        };
      }

      raster.on(&#x27;beforeoperations&#x27;, function(event) {
        event.data.counts &#x3D; createCounts(minVgi, maxVgi, bins);
        event.data.threshold &#x3D; raster.get(&#x27;threshold&#x27;);
      });

      raster.on(&#x27;afteroperations&#x27;, function(event) {
        schedulePlot(event.resolution, event.data.counts, event.data.threshold);
      });

      var map &#x3D; new ol.Map({
        layers: [
          new ol.layer.Tile({
            source: bing
          }),
          new ol.layer.Image({
            source: raster
          })
        ],
        target: &#x27;map&#x27;,
        view: new ol.View({
          center: [-9651695, 4937351],
          zoom: 13,
          minZoom: 12,
          maxZoom: 19
        })
      });


      var timer &#x3D; null;
      function schedulePlot(resolution, counts, threshold) {
        if (timer) {
          clearTimeout(timer);
          timer &#x3D; null;
        }
        timer &#x3D; setTimeout(plot.bind(null, resolution, counts, threshold), 1000 / 60);
      }

      var barWidth &#x3D; 15;
      var plotHeight &#x3D; 150;
      var chart &#x3D; d3.select(&#x27;#plot&#x27;).append(&#x27;svg&#x27;)
          .attr(&#x27;width&#x27;, barWidth * bins)
          .attr(&#x27;height&#x27;, plotHeight);

      var chartRect &#x3D; chart[0][0].getBoundingClientRect();

      var tip &#x3D; d3.select(document.body).append(&#x27;div&#x27;)
          .attr(&#x27;class&#x27;, &#x27;tip&#x27;);

      function plot(resolution, counts, threshold) {
        var yScale &#x3D; d3.scale.linear()
            .domain([0, d3.max(counts.values)])
            .range([0, plotHeight]);

        var bar &#x3D; chart.selectAll(&#x27;rect&#x27;).data(counts.values);

        bar.enter().append(&#x27;rect&#x27;);

        bar.attr(&#x27;class&#x27;, function(count, index) {
          var value &#x3D; counts.min + (index * counts.delta);
          return &#x27;bar&#x27; + (value &gt;&#x3D; threshold ? &#x27; selected&#x27; : &#x27;&#x27;);
        })
            .attr(&#x27;width&#x27;, barWidth - 2);

        bar.transition().attr(&#x27;transform&#x27;, function(value, index) {
          return &#x27;translate(&#x27; + (index * barWidth) + &#x27;, &#x27; +
              (plotHeight - yScale(value)) + &#x27;)&#x27;;
        })
            .attr(&#x27;height&#x27;, yScale);

        bar.on(&#x27;mousemove&#x27;, function(count, index) {
          var threshold &#x3D; counts.min + (index * counts.delta);
          if (raster.get(&#x27;threshold&#x27;) !&#x3D;&#x3D; threshold) {
            raster.set(&#x27;threshold&#x27;, threshold);
            raster.changed();
          }
        });

        bar.on(&#x27;mouseover&#x27;, function(count, index) {
          var area &#x3D; 0;
          for (var i &#x3D; counts.values.length - 1; i &gt;&#x3D; index; --i) {
            area +&#x3D; resolution * resolution * counts.values[i];
          }
          tip.html(message(counts.min + (index * counts.delta), area));
          tip.style(&#x27;display&#x27;, &#x27;block&#x27;);
          tip.transition().style({
            left: (chartRect.left + (index * barWidth) + (barWidth / 2)) + &#x27;px&#x27;,
            top: (d3.event.y - 60) + &#x27;px&#x27;,
            opacity: 1
          });
        });

        bar.on(&#x27;mouseout&#x27;, function() {
          tip.transition().style(&#x27;opacity&#x27;, 0).each(&#x27;end&#x27;, function() {
            tip.style(&#x27;display&#x27;, &#x27;none&#x27;);
          });
        });

      }

      function message(value, area) {
        var acres &#x3D; (area / 4046.86).toFixed(0).replace(/\B(?&#x3D;(\d{3})+(?!\d))/g, &#x27;,&#x27;);
        return acres + &#x27; acres at&lt;br&gt;&#x27; + value.toFixed(2) + &#x27; VGI or above&#x27;;
      }
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;</code></pre>
      </div>
    </div>

    <script src="./resources/common.js"></script>
    <script src="./resources/prism/prism.min.js"></script>
    <script src="loader.js?id=raster"></script>
  </body>
  <script>
  var packageUrl = 'https://raw.githubusercontent.com/openlayers/openlayers.github.io/build/package.json';
  fetch(packageUrl).then(function(response) {
    return response.json();
  }).then(function(json) {
    var latestVersion = json.version;
    document.getElementById('latest-version').innerHTML = latestVersion;
    var url = window.location.href;
    var branchSearch = url.match(/\/([^\/]*)\/examples\//);
    var cookieText = 'dismissed=-' + latestVersion + '-';
    var dismissed = document.cookie.indexOf(cookieText) != -1;
    if (!dismissed && /^v[0-9\.]*$/.test(branchSearch[1]) && '4.4.2' != latestVersion) {
      var link = url.replace(branchSearch[0], '/latest/examples/');
      fetch(link, {method: 'head'}).then(function(response) {
        var a = document.getElementById('latest-link');
        a.href = response.status == 200 ? link : '../../latest/examples/';
      });
      var latestCheck = document.getElementById('latest-check');
      latestCheck.style.display = '';
      document.getElementById('latest-dismiss').onclick = function() {
        latestCheck.style.display = 'none';
        document.cookie = cookieText;
      }
    }
  });
  </script>
</html>
